package com.lhy.service;

import com.lhy.pojo.Files;
import com.lhy.pojo.Gas;
import com.lhy.pojo.Log;
import com.lhy.pojo.Miner;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.result.DeleteResult;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LogService {
    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private GridFsTemplate gridFsTemplate;


    public String saveMultipartFile(MultipartFile multipartFile) throws Exception{
        //文件上传至数据库
        String fileName=multipartFile.getOriginalFilename();
        //输入流
        InputStream ins=multipartFile.getInputStream();
        String contentType=multipartFile.getContentType();
        ObjectId objectId=gridFsTemplate.store(ins,fileName,contentType);
        //返回文件id
        String id=objectId.toString();
        return id;
    }

    public Map<String,Object> selectAll(){
        List<GridFSFile> fileList = new ArrayList<GridFSFile>();
        gridFsTemplate.find(new Query()).into(fileList);
        Map<String,Object> gasResult =new HashMap<>();

        if(fileList==null || fileList.isEmpty()){
            gasResult.put("code","400");
            gasResult.put("message","没有相关信息");
        }else{
            gasResult.put("code","0");
            gasResult.put("count",fileList.size());
            gasResult.put("data",fileList);
        }

        return gasResult;
    }

    //查询所有日志
    public Map<String,Object> selectLogList(){
        List<Log> list = mongoTemplate.findAll(Log.class,"log");
        Map<String,Object> result =new HashMap<>();
        if(list==null || list.isEmpty()){
            result.put("code","400");
            result.put("message","没有相关信息");
        }else{
            result.put("code","0");
            result.put("count",list.size());
            result.put("data",list);
        }
        return result;
    }

}
